package com.nonintrusive.client.tabs.answerquestion;

import java.util.ArrayList;

import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.widget.ListView;

import com.nonintrusive.client.GlobalNonIntrusive;
import com.nonintrusive.client.Question;
import com.nonintrusive.client.database.ClientDB;
import com.nonintrusive.client.send.R;

public class AnswerQuestionActivity extends Activity {
	protected static final String TAG = "AnswerQuestionActivity";

	private ArrayList<Question> mQuestions;
	private AnswerQuestionAdapter mAdapter;
	private long mLastUpdate;
	private Handler mHandler;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.answer_question);

		mLastUpdate = 0;
		mHandler = new Handler();

		ListView list = (ListView) findViewById(android.R.id.list);

		mQuestions = GlobalNonIntrusive.answerQuestions = new ArrayList<Question>();
		mAdapter = GlobalNonIntrusive.answerQAdapter = new AnswerQuestionAdapter(
				this, R.layout.question_item, mHandler);
		list.setAdapter(mAdapter);
	}

	@Override
	public void onResume() {
		super.onResume();
		final ArrayList<Question> questions = mQuestions;
		final AnswerQuestionAdapter adapter = mAdapter;
		new Thread(new Runnable() {
			@Override
			public void run() {
				Cursor cursor = managedQuery(ClientDB.CONTENT_URI, null,
						ClientDB.TIMESTAMP + " > " + mLastUpdate + " and "
								+ ClientDB.IS_MY_QUESTION + " = " + "0", null,
						null);
				mLastUpdate = System.currentTimeMillis();

				int id_i = cursor.getColumnIndex(ClientDB.QUESTION_ID);
				int message_i = cursor.getColumnIndex(ClientDB.MESSAGE);
				int myQ_i = cursor.getColumnIndex(ClientDB.IS_MY_QUESTION);
				int isAnsw_i = cursor.getColumnIndex(ClientDB.IS_ANSWERED);

				while (cursor.moveToNext()) {
					final Question item = new Question();
					item.id = cursor.getInt(id_i);
					boolean exists = false;
					for (Question question : questions) {
						if (question.equals(item)) {
							if (cursor.getInt(isAnsw_i) == 1) {
								question.isAnswered = true;
							}
							runOnUiThread(new Runnable() {
								public void run() {
									adapter.notifyDataSetChanged();
								}
							});
							exists = true;
							break;
						}
					}
					if (exists)
						continue;
					item.message = cursor.getString(message_i);
					if (cursor.getInt(myQ_i) == 1)
						item.isMine = true;
					else
						item.isMine = false;

					if (cursor.getInt(isAnsw_i) == 1)
						item.isAnswered = true;
					else
						item.isAnswered = false;

					mHandler.post(new Runnable() {
						@Override
						public void run() {
							questions.add(item);
							adapter.notifyDataSetChanged();
						}
					});
				}
			}
		}).start();
	}

}
